package com.mb.search.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

@Configuration
public class ElasticsearchConfig {

    @Value("${sqhz.es.nodes}")
    private List<String> nodes;

    @Bean
    public TransportClient init(){
        PreBuiltTransportClient client = new PreBuiltTransportClient(Settings.EMPTY);

        for (String node : nodes) {
            String host = node.split(":")[0];
            Integer prot = Integer.parseInt(node.split(":")[1]);
            InetSocketTransportAddress address = null;
            try {
                address = new InetSocketTransportAddress(InetAddress.getByName(host), prot);
            } catch (UnknownHostException e) {
                e.printStackTrace();
                System.out.println("UnknownHostException");
            }
            client.addTransportAddress(address);
        }
        return client;
    }
}
